﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Styx;
using Styx.Helpers;
using System.Threading;

namespace BuddyManager
{
    public partial class NewUI : Form
    {
        public bool AddingTask;

        public NewUI()
        {
            InitializeComponent();
        }

        public void NewUI_Load(object sender, EventArgs e)
        {
            BuddyManager.LoadSettings();
            if (BuddyManager.TaskList.Count <= 0) return;
            foreach (var task in BuddyManager.TaskList)
            {
                var newItem = new ListViewItem((listView1.Items.Count + 1).ToString());
                
                newItem.SubItems.Add(task.BotBase);
                newItem.SubItems.Add(task.Zone);
                newItem.SubItems.Add(task.SwitchInt.ToString());
                newItem.SubItems.Add(task.SwitchOn);
                newItem.SubItems.Add(task.ProfileList.Count.ToString());
                string tmpStr = "";
                foreach (var str in task.ProfileList)
                {
                    if (String.IsNullOrEmpty(tmpStr))
                        tmpStr = str;
                    else
                        tmpStr = string.Format("{0};{1}", tmpStr, str);
                }
                if (!String.IsNullOrEmpty(tmpStr))
                    newItem.SubItems.Add(tmpStr);

                listView1.Items.Add(newItem);
            }
            SetNumbers();
            LogOutAfter.Checked = BuddyManager.uSettings.LogOutAfter;
            LoopAfter.Checked = !(LogOutAfter.Checked);
            LoopHours.Value = BuddyManager.uSettings.TotalHr;
            LoopMinutes.Value = BuddyManager.uSettings.TotalMin;
            cbVendorForce.Checked = BuddyManager.uSettings.ForceNext;
            cbMail.Checked = BuddyManager.uSettings.Mail;
            cbRepairSell.Checked = BuddyManager.uSettings.Vendor;
            RandTasksWhileRunning.Checked = BuddyManager.uSettings.Randomize;
            shortBreakcb.Checked = BuddyManager.uSettings.shortBreak;
            this.Update();
            this.Focus();
        }





        public void SendTask(bool AddTask)
        {
            try
            {
                AddingTask = AddTask;
                Form popUp;
                if (AddTask)
                {
                    popUp = new TaskingPopup(true, new ListViewItem());
                }
                else
                {
                    popUp = new TaskingPopup(false, listView1.Items[listView1.SelectedIndices[0]]);
                }
                popUp.FormClosing += new FormClosingEventHandler(PopUp_FormClosing);
                popUp.StartPosition = FormStartPosition.CenterScreen;
                popUp.Show();
            }
            catch (Exception e)
            { }
        }

        public void PopUp_FormClosing(object sender, EventArgs eve)
        {
            try
            {
                var form = (TaskingPopup)sender;
                if (form.Cancelled) return;
                //Logging.Write("OUTSIDE FIRST IF");
                if (AddingTask)
                {
                    var newItem = new ListViewItem();
                    for (int i = 1; i < 7; i++)
                    {
                        newItem.SubItems.Add(form.Item.SubItems[i].Text);
                    }
                    listView1.Items.Add(newItem);
                    //Logging.Write("ADDING IF");
                }
                else
                {
                    ListViewItem editItem = listView1.Items[form.Item.Index];
                    //Logging.Write("LISTVIEW INDEX");
                    for (int i = 1; i < 7; i++)
                    {
                        listView1.Items[editItem.Index].SubItems[i] = form.Item.SubItems[i];
                        Thread.Sleep(100);
                        //Logging.Write("INSIDE FOR I");
                    }
                }
                SetNumbers();
            }
            catch (Exception e)
            { }
        }

        public void DelTask()
        {
            try
            {
                listView1.Items.RemoveAt(listView1.SelectedItems[0].Index);
                SetNumbers();
            }
            catch (Exception e)
            { }
        }

        public void SetNumbers()
        {
            foreach (ListViewItem item in listView1.Items)
            {
                item.Text = item.Index.ToString();
            }
        }

        private void ButtonAddTask_Click(object sender, EventArgs e)
        {
            SendTask(true);
        }

        private void ButtonEditTask_Click(object sender, EventArgs e)
        {
            SendTask(false);
        }

        private void ButtonDeleteTask_Click(object sender, EventArgs e)
        {
            DelTask();
        }

        private void ShiftListViewItem(ref ListView lv, bool moveUp)
        {
            string cache;
            int selIdx;

            selIdx = lv.SelectedItems[0].Index;
            if (moveUp)
            {
                // ignore moveup of row(0)
                if (selIdx == 0)
                    return;

                // move the subitems for the previous row
                // to cache to make room for the selected row
                for (int i = 0; i < lv.Items[selIdx].SubItems.Count; i++)
                {
                    cache = lv.Items[selIdx - 1].SubItems[i].Text;
                    lv.Items[selIdx - 1].SubItems[i].Text =
                      lv.Items[selIdx].SubItems[i].Text;
                    lv.Items[selIdx].SubItems[i].Text = cache;
                }
                lv.Items[selIdx - 1].Selected = true;
                lv.Refresh();
                lv.Focus();
            }
            else
            {
                // ignore movedown of last item
                if (selIdx == lv.Items.Count - 1)
                    return;
                // move the subitems for the next row
                // to cache so we can move the selected row down
                for (int i = 0; i < lv.Items[selIdx].SubItems.Count; i++)
                {
                    cache = lv.Items[selIdx + 1].SubItems[i].Text;
                    lv.Items[selIdx + 1].SubItems[i].Text =
                      lv.Items[selIdx].SubItems[i].Text;
                    lv.Items[selIdx].SubItems[i].Text = cache;
                }
                lv.Items[selIdx + 1].Selected = true;
                lv.Refresh();
                lv.Focus();
            }
            SetNumbers();
        }

        private void buttonShiftUp_Click(object sender, EventArgs e)
        {
            ShiftListViewItem(ref listView1, true);
        }

        private void buttonShiftDown_Click(object sender, EventArgs e)
        {
            ShiftListViewItem(ref listView1, false);
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (LoopAfter.Checked)
            {
                LoopHours.Enabled = true;
                LoopMinutes.Enabled = true;
            }
            else
            {
                LoopHours.Enabled = false;
                LoopMinutes.Enabled = false;
            }
        }

        private void buttonRandomTaskTimes_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lItem in listView1.Items)
            {
                if (RandTimeMax.Value <= 0) return;
                if(lItem.SubItems[4].Text != "Nodes")
                    lItem.SubItems[3].Text = RanNum(Convert.ToInt32(RandTimeMin.Value), Convert.ToInt32(RandTimeMax.Value)).ToString();
            }
            listView1.Update();
            listView1.Focus();
        }

        public int RanNum(int min, int max)
        {
            return _rnd.Next(min, max + 1);
        }

        readonly Random _rnd = new Random();
        public double RandDouble()
        {
            return _rnd.NextDouble();
        }

        private void buttonForceLoadSettings_Click(object sender, EventArgs e)
        {
            InternalSave();
            BuddyManager.SaveSettings();
            BuddyManager.LoadSettings();
        }

        private void Save_Click(object sender, EventArgs e)
        {
            InternalSave();
            BuddyManager.SaveSettings();
        }

        private void InternalSave()
        {
            BuddyManager.uSettings.LogOutAfter = LogOutAfter.Checked;
            BuddyManager.uSettings.Mail = cbMail.Checked;
            BuddyManager.uSettings.Vendor = cbVendorForce.Checked;
            BuddyManager.uSettings.TotalHr = Convert.ToInt32(LoopHours.Value);
            BuddyManager.uSettings.TotalMin = Convert.ToInt32(LoopMinutes.Value);
            BuddyManager.uSettings.Randomize = RandTasksWhileRunning.Checked;
            BuddyManager.uSettings.shortBreak = shortBreakcb.Checked;
            BuddyManager.TaskList.Clear();
            foreach (ListViewItem item in listView1.Items)
            {
                BuddyManager.TaskStruct tmpTask = new BuddyManager.TaskStruct();
                tmpTask.BotBase = item.SubItems[1].Text;
                tmpTask.Zone = item.SubItems[2].Text;
                tmpTask.SwitchInt = item.SubItems[3].Text.ToInt32();
                tmpTask.SwitchOn = item.SubItems[4].Text;
                var str = item.SubItems[6].Text;
                if (!String.IsNullOrEmpty(str))
                {
                    var strA = str.Split(new Char[] { ';' });
                    foreach (var s in strA)
                    { s.Replace(";", ""); if (!String.IsNullOrEmpty(s)) { tmpTask.ProfileList.Add(s); } }
                }
                BuddyManager.TaskList.Add(tmpTask);
            }
            BuddyManager.Log("Successfully updated variables.");
        }

        private void SaveClose_Click(object sender, EventArgs e)
        {
            InternalSave();
            BuddyManager.SaveSettings();
            this.Close();
            this.Dispose();
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            SendTask(false);
        }

        private void buttonRandomizeNodes_Click(object sender, EventArgs e)
        {

            foreach (ListViewItem lItem in listView1.Items)
            {
                if (RandTimeMax.Value <= 0) return;
                if (lItem.SubItems[4].Text != "Minutes")
                    lItem.SubItems[3].Text = RanNum(Convert.ToInt32(RandTimeMin.Value), Convert.ToInt32(RandTimeMax.Value)).ToString();
            }
            listView1.Update();
            listView1.Focus();
        }

        private void buttonShowBaseStartTime_Click(object sender, EventArgs e)
        {
            BuddyManager.TotalRunningTime();
        }

        private void buttonShowTaskRunningTime_Click(object sender, EventArgs e)
        {
            BuddyManager.TotalBaseTime();
        }


    }
}
